package com.chilx.aop.aspect;

import com.chilx.aop.annotation.LogAnnotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author chilx
 * @date 2021/3/31
 **/
@Aspect
@Component
public class LogAnnotationAspect {


    /**
     * 切点
     */
    @Pointcut("@annotation(com.chilx.aop.annotation.LogAnnotation)")
    public void logPointCut() {

    }


    /**
     * 前置通知: 方法执行前调用
     */
    @Before(value = "logPointCut() && @annotation(logInfo)", argNames = "point,logInfo")
    public void before(JoinPoint point, LogAnnotation logInfo) {
        // 参数
        Object[] args = point.getArgs();
        System.out.println();
        System.out.println("前置通知" + "-->" + logInfo.title() + "--" + logInfo.remark());

    }
    /**
     * 后置通知： 方法执行后调用，若方法出现异常，不执行
     */
    @After(value = "logPointCut() && @annotation(logInfo)", argNames = "point,logInfo")
    public void after(JoinPoint point, LogAnnotation logInfo) {
        System.out.println("后置通知" + "-->" + logInfo.title() + "--" + logInfo.remark());

    }
    /**
     * 返回： 方法执行后调用，若方法出现异常，不执行
     */
    @AfterReturning(value = "logPointCut() && @annotation(logInfo)", argNames = "point,logInfo")
    public void afterReturning(JoinPoint point, LogAnnotation logInfo) {
        System.out.println("后置通知" + "-->" + logInfo.title() + "--" + logInfo.remark());

    }

    /**
     * 环绕通知
     */
    @Around(value = "logPointCut() && @annotation(logInfo)", argNames = "point,logInfo")
    public void around(ProceedingJoinPoint point, LogAnnotation logInfo) throws Throwable {
        System.out.println("执行方法前");
        Object proceed = point.proceed(point.getArgs());
        System.out.println("执行方法后");
        System.out.println("环绕通知" + "-->" + logInfo.title() + "--" + logInfo.remark());

    }

    /**
     * 异常通知：方法抛出异常时执行
     */
    @AfterThrowing(value = "logPointCut() && @annotation(logInfo)", argNames = "point,logInfo,e", throwing = "e")
    public void afterThrowing(JoinPoint point, LogAnnotation logInfo, Exception e) {

        System.out.println("异常通知" + "-->" + logInfo.title() + "--" + logInfo.remark());
        System.out.println(e.getMessage());
    }


}
